package com.xiao.mall.foundation.config;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Pageable;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.AlternateTypeRules;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("spring.application.name")
    private String applicationName;

    private AlternateTypeRule pageableTypeRule() {
        return AlternateTypeRules.newRule(Pageable.class, Page.class, 1);
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(applicationName)
                .apiInfo(apiInfo())
                .alternateTypeRules(pageableTypeRule())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xiao"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 用于定义API主界面的信息，比如可以声明所有的API的总标题、描述、版本
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("淘不庭商城API")
                .description("淘不庭商城API")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }

    @ApiModel
    @Getter
    @Setter
    static class Page {
        @ApiModelProperty("页码，第几页，从1开始")
        private Integer page;

        @ApiModelProperty("每页记录数")
        private Integer size;

        @ApiModelProperty("排序，格式：字段名(,asc|desc)。默认asc")
        private List<String> sort;
    }
}
